<template>
    <div>
        <canvas id="myCanvas"></canvas>
        <img :src="base64Image" alt="">
    </div>
</template>

<script setup>
import { onMounted, reactive, ref }  from 'vue'
import guoBo from '@/assets/images/guobo.png'
import { fixedDataType } from 'element-plus/es/components/table-v2/src/common';

onMounted(() => {
    createCanvas()
})


const canvas = ref()
const canvasW = 500
const base64Image = ref('')

const data = reactive({
    // 身份证号码
    docNo: '362401199610202900',
    // 订单编号
    orderNum: 'SK24062318622981',
    // 下单时间
    orderTime: '2024-06-23 18:42:13',
    // 订单金额
    orderAmount: '¥ 0.0',
    //姓名
    name: '曹刚煌',
    // 二维码
    qrCode: '',
    // 位置
    location: '国家博物馆北门西侧入口',
    // 状态
    status: '待核验'
})

const createCanvas = () => {
    const canvas = document.getElementById('myCanvas')
    canvas.width = canvasW
    canvas.height = 0
    const ctx = canvas.getContext('2d')
    
    const img = new Image()
    img.src = guoBo
    img.onload = function() {

        const imgW = img.width
        const imgH = img.height
        const aspectRatio = imgW / imgH

        const dynH = canvasW / aspectRatio

        canvas.height = dynH

        ctx.drawImage(img, 0, 0, canvasW, dynH)



        //  订单编号
        handleCover(ctx, 26, 140, data.orderNum, {fontSize: 18, color: 'rgba(27, 26, 27, .8)'})
        // 下单时间
        handleCover(ctx, 295, 205, data.orderTime, {fontSize: 19, color: 'rgba(23, 24, 25, .8)'})
        // 订单金额
        handleCover(ctx, 428, 240, data.orderAmount)
        // 姓名
        handleCover(ctx, 46, 336, data.name)
         // 身份证号码
        handleCover(ctx, 146, 374, data.docNo, {fontSize: 19, color: 'rgba(142, 143, 144, .8)'})
        handleCover(ctx, 46, 374, '身份证')
        // 地址
        handleCover(ctx, 46, 687, data.location, {fontSize: 16})
        // 下单时间
        handleCover(ctx, 47, 722, data.orderTime, {fontSize: 16, color: '#bbb9b9'})
        // 状态
        handleCover(ctx, 376, 710, data.status, {fontSize: 18})


        // 生成base64
        base64Image.value = canvas.toDataURL('image/jpeg')

        console.log(base64Image.value, 'base64Image')
    } 
}

const handleCover = (ctx, x, y, v, style = null) => {

    const { fontSize, color } = style || {
        fontSize: 20,
        color: '#5f5f5f'
    }
    ctx.beginPath()
    ctx.font = `${fontSize}px SimSun`
    ctx.fillStyle = color
    ctx.fillText(v, x, y);
}


// 画框
const canvasFrame = (ctx, x, y , w, h) => {
    ctx.strokeRect(x, y, w, h)
}

</script>

<style lang="scss" scoped>
.image {
    display: block;
    width: 100%;
}
</style>